package com.shut.vehicle.service.impl;

import com.github.pagehelper.PageHelper;
import com.shut.vehicle.dao.DeviceDao;
import com.shut.vehicle.dao.ServiceRecordDao;
import com.shut.vehicle.exception.ServiceException;
import com.shut.vehicle.pojo.Device;
import com.shut.vehicle.pojo.ServiceRecord;
import com.shut.vehicle.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 卢斌
 */
@Service
public class DeviceServiceImpl implements DeviceService {


    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private ServiceRecordDao serviceRecordDao;


    @Override
    @Transactional
    public void createDeviceInfo(Device device) {
        Device.checkDeviceParam(device);
        deviceDao.addDevice(device);
    }

    @Override
    @Transactional
    public void updateDeviceInfo(Device device) {
        Device.checkDeviceParam(device);
        if (device.getId() == null) {
            throw new ServiceException("请指定修改目标设备");
        }
        deviceDao.updateDevice(device);
    }

    @Override
    @Transactional
    public void deleteDeviceInfo(Device device) {
        if (device.getId() == null) {
            throw new ServiceException("请指定删除的目标设备");
        }
        List<ServiceRecord> unfinishedRecord = serviceRecordDao.listServiceRecord(device.getId(), null, false);
        if (!unfinishedRecord.isEmpty()) {
            throw new ServiceException("设备已被预约，暂时无法删除");
        }
        deviceDao.deleteDevice(device);
    }

    @Override
    public List<Device> listDeviceSearchLocation(String locationLikeName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return deviceDao.listDevice(locationLikeName);
    }
    
}
